# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def maxSumBST(self, root: TreeNode) -> int:
        def func(node, ans):
            if node is None:
                return (0, None, None, True)
            leftMaxRes, leftMinVal, leftMaxVal, leftBst = func(node.left, ans)
            rightMaxRes, rightMinVal, rightMaxVal, rightBst = func(
                node.right, ans)

            if leftBst and rightBst and (leftMaxVal is None
                                         or node.val > leftMaxVal) and (
                                             rightMinVal is None
                                             or node.val < rightMinVal):
                res = leftMaxRes + rightMaxRes + node.val
                minVal = min(leftMinVal
                             if leftMinVal is not None else 2**31, node.val)
                maxVal = max(
                    rightMaxVal
                    if rightMaxVal is not None else -2**31, node.val)
            else:
                res = -2**31
                minVal = 2**31
                maxVal = -2**31
            ans[0] = max(res, ans[0])

            return (res, minVal, maxVal, leftBst and rightBst)

        ans = [0]

        func(root, ans)

        return ans[0]
